/*************************************************************************
> File Name: sql.hpp
> Author: hzy
> Created Time: 2023-08-17 09:58:52
> Description:
************************************************************************/
#include "array.h"

template <class T>
MyArray<T>::MyArray()
{
    Size = 0;
    Capacity = 1;
    this->Data = new T[Capacity];
}

template <class T>
MyArray<T>::~MyArray()
{
    delete[] Data;
}

// 获取动态数组的容量
template <class T>
int MyArray<T>::getCapacity()
{
    return this->Capacity;
}

// 获取动态数组的大小
template <class T>
int MyArray<T>::getSize()
{
    return this->Size;
}

// 判断动态数组是否为空
template <class T>
bool MyArray<T>::isEmpty()
{
    return Size == 0;
}

// 尾插法插入
template <class T>
void MyArray<T>::pushBack(T value)
{
    // 动态数组已经满了
    if (Size == Capacity)
    {
        // 将动态数组容量扩大两倍
        reSize(Capacity * 2);
    }
    Data[Size++] = value;
}

// 删除末尾的数据元素
template <class T>
void MyArray<T>::popBack()
{
    if (Size > 0)
    {
        Size--;
        if (Size <= Capacity / 2)
        {
            reSize(Capacity / 2);
        }
    }
}

// 重载[]操作符(访问指定位置的元素)
template <class T>
T &MyArray<T>::operator[](int location) const
{
    if (location >= 0 && location < this->Size)
    {
        return Data[location];
    }
    else
    {
        cout << "访问位置出错！！！" << endl;
    }
}

template <class T>
void MyArray<T>::showArr()
{
    for (int i = 0; i < getSize(); i++)
    {
        cout << this->Data[i] << ",";
    }
    cout << endl;
}

// 调整动态数组的容量
template <class T>
void MyArray<T>::reSize(int newCapacity)
{
    T *newData = new T[newCapacity];
    for (int i = 0; i < Size; i++)
    {
        newData[i] = Data[i];
    }
    Capacity = newCapacity;
    delete[] Data;
    Data = newData;
}

// 重载输出操作符<<
template <class U>
ostream &operator<<(ostream &os, const MyArray<U> &arr)
{
    for (int i = 0; i < arr.Size; i++)
    {
        os << arr[i] << " , ";
    }
    os << endl;
    return os;
}
